package com.mission.shaco.warehouse

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import com.androidquery.AQuery
import com.androidquery.callback.AjaxCallback
import com.androidquery.callback.AjaxStatus
import com.mission.shaco.warehouse.stockout.MultiActivity
import com.mission.shaco.warehouse.stockout.SingleActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONArray
import android.view.ViewGroup
import android.widget.*
import com.mission.shaco.warehouse.models.ClientConfig.*
import org.json.JSONObject
import java.io.Serializable
import com.mission.shaco.warehouse.models.UpdateManager
import android.widget.TextView
import android.app.ActivityManager
import android.app.Activity
import com.mission.shaco.warehouse.models.ClientConfig
import com.mission.shaco.warehouse.models.Tool
import com.mission.shaco.warehouse.stockin.StockInActivity


class MainActivity : BaseActivity(),View.OnClickListener, RadioGroup.OnCheckedChangeListener, View.OnLongClickListener {


    override fun onLongClick(v: View?): Boolean {
        ClientConfig.runDevelop = !ClientConfig.runDevelop
        ClientConfig.setValue("mode", ClientConfig.runDevelop)
        reloadTestLabel()
        return true
    }

    fun reloadTestLabel(){
        if(ClientConfig.runDevelop){
            txtDevelop.text = "测试环境"
        }else{                                // 之前是正式环境
            txtDevelop.text = "正式环境"
        }
    }


    lateinit var preference: SharedPreferences
    private var testPre: Int = 0
    var operatorName:String = ""
    private val handler = Handler()
    private var singleBtnText:String = ""
    private var multiBtnText:String = ""
    private var multimultiBtnText:String = ""


    private val task = object : Runnable {
        override fun run() {
            // TODO Auto-generated method stub
            handler.postDelayed(this, 5 * 1000)//设置延迟时间，此处是5秒

            if(isForeground(this@MainActivity)) {
                var t = Thread(getRestTodayThread)
                t.start()
            }
        }
    }

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {

        when(checkedId){
            radioNormal.id -> { isSpecial = 0 }
            radioSpecial.id -> { isSpecial = 1 }
            radioLarge.id -> { isSpecial = 2 }
        }

        var t = Thread(getRestTodayThread)
        t.start()

    }


    fun isForeground(activity: Activity): Boolean {
        return isForeground(activity, activity.javaClass.name)
    }

    /**
     * 判断某个界面是否在前台

     * @param context   Context
     * *
     * @param className 界面的类名
     * *
     * @return 是否在前台显示
     */
    fun isForeground(context: Context?, className: String): Boolean {
        if (context == null || TextUtils.isEmpty(className))
            return false
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = am.getRunningTasks(1)
        if (list != null && list.size > 0) {
            val cpn = list[0].topActivity
            if (className == cpn.className)
                return true
        }
        return false
    }

    var getRestTodayThread: Runnable = Runnable {
        try {
            val aq:AQuery = AQuery(this)

            val params = HashMap<String, Any>()
            var map = JSONObject()
            map.put("splitType", isSpecial)
            params.put("datas", map)

            aq.ajax(getHostUrl(JOSN_GET_REST_TODAY_PATH),params, String::class.java,  object : AjaxCallback<String>() {

                override fun callback(url: String, result: String, status: AjaxStatus) {
                    if(status.code == 200){
                        var response:JSONObject = JSONObject(result)
                        if(response.getInt("status") == 1) {
                            var json = response.getJSONObject("info")

                            if(TextUtils.isEmpty(singleBtnText)){
                                singleBtnText = stockOutSingle.text as String
                            }
                            if(TextUtils.isEmpty(multiBtnText)){
                                multiBtnText = stockOutMulti.text as String
                            }
                            if(TextUtils.isEmpty(multimultiBtnText)){
                                multimultiBtnText = stockOutMultiMulti.text as String
                            }

                            var singleQty =   "0"
                            var multiQty = "0"
                            var multiMultiQty = "0"

                            if(json.has("single")) {
                                singleQty = json.getString("single")
                            }

                            if(json.has("multi")) {
                                multiQty = json.getString("multi")
                            }

                            if(json.has("multi_multi")) {
                                multiMultiQty = json.getString("multi_multi")
                            }

                            stockOutSingle.text = singleBtnText + "[" + singleQty + "]"
                            stockOutMulti.text = multiBtnText + "["+ multiQty +"]"
                            stockOutMultiMulti.text = multimultiBtnText + "["+ multiMultiQty +"]"

                        }
                    }else{
                    }
                }
            })

        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }

    public fun startUpdateManager(){
        val manager = UpdateManager(this)
    }

    var hostUpdateThread: Runnable = Runnable {
        try {
            val aq: AQuery = AQuery(this)
            val params = HashMap<String, Any>()

            var map:HashMap<String,String> = HashMap()
            val expreTime :Long = 60 * 60 * 24

            aq.ajax(APP_CHECK_URL, String::class.java, expreTime,  object : AjaxCallback<String>() {

                override fun callback(url: String, result: String, status: AjaxStatus) {
                    if(status.code == 200) {
                        APP_IP = "http://" + result + ":8087/"
                        startUpdateManager()
                    }else{

                    }
                }
            })

        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var d = ClientConfig.getBoolean("mode")
        if(d !== null){
            ClientConfig.runDevelop = d
        }

        var role = this.getRole()
        var canUseBtnList = role.getMenu()

        for (key in canUseBtnList.keys()){
            findViewById(canUseBtnList.getInt(key)).visibility = View.VISIBLE
        }

        stockOutSingle.setOnClickListener(this)
        stockOutMulti.setOnClickListener(this)
        stockOutMultiMulti.setOnClickListener(this)
        btnStockChange.setOnClickListener(this)
        btnStockChangeStock.setOnClickListener(this)
        btnCheckQty.setOnClickListener(this)
        btnChangeOperator.setOnClickListener(this)
        txtCurrentOperator.text = opreateName
        btnStockIn.setOnClickListener(this)
        radioGroup.setOnCheckedChangeListener (this)
        btnReceive.setOnClickListener(this)
        txtDevelop.setOnLongClickListener(this)

        handler.post(task)

        var u:Thread = Thread(hostUpdateThread)
        u.start()
    }

    override fun onClick(v: View?) {
        if(TextUtils.isEmpty(opreateName)){

        }else {
            when (v?.id) {

                stockOutSingle.id -> startActivity(Intent(this, SingleActivity::class.java))
                stockOutMulti.id -> startMultiActivity(ORDER_PICK_TYPE_SINGLE_MULTI)
                stockOutMultiMulti.id->  startMultiActivity(ORDER_PICK_TYPE_MULTI_MULTI)
                btnStockChange.id -> startActivity(Intent(this, StockChangeActivity::class.java))
                btnStockChangeStock.id -> startActivity(Intent(this, StockChangeByStockActivity::class.java))
                btnCheckQty.id -> startActivity(Intent(this, CheckQtyActivity::class.java))
                btnStockIn.id -> startActivity(Intent(this, StockInActivity::class.java))
                btnReceive.id -> startActivity(Intent(this, ReciveActivity::class.java))

                btnChangeOperator.id -> {
                    this.getRole().clear()
                    Tool().serializableObject("role",this.getRole())
                    startActivity(Intent(this, LoginActivity::class.java))
                    finish()
                }
            }
        }
    }

    fun startMultiActivity(type:Int){
        var intent: Intent = Intent(this, MultiActivity::class.java)
        intent.putExtra("orderPickType",type)
        this.startActivity(intent)
    }

    fun initOpreator(){
        val name = getOpreateName()
        if(!TextUtils.isEmpty(name)){
            operatorName = name
        }
    }

    class ListOrderAdapter(context: Context) : BaseAdapter(), Serializable {

        public var sList: JSONArray = JSONArray()
        private val mInflator: LayoutInflater

        init {
            this.mInflator = LayoutInflater.from(context)
        }

        override fun getCount(): Int {
            return sList.length()
        }


        override fun getItem(position: Int): JSONObject {
            return sList.get(position) as JSONObject
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
            val view: View?
            val vh: ListOpreatorHolder
            if (convertView == null) {
                view = this.mInflator.inflate(R.layout.spiner_opreator, parent, false)
                vh = ListOpreatorHolder(view)
                view.tag = vh

            } else {
                view = convertView
                vh = view.tag as ListOpreatorHolder
            }

            val item:JSONObject = this.getItem(position)
            vh.name.text = item.getString("name")
            return view
        }
    }

    public class ListOpreatorHolder(row: View?)  {

        public val name: TextView

        init {
            this.name = row?.findViewById ( R.id.opreator_name ) as TextView
        }
    }


}

